<template>
  <div class="security-monitor">
    <!-- 头部 -->
    <div class="header">
      <div class="title-group">
        <el-icon class="main-icon"><Monitor /></el-icon>
        <h1>数据安全监测系统</h1>
      </div>
      <div class="status-group">
        <el-tag :type="systemStatus.firewall ? 'success' : 'danger'" effect="dark" class="status-tag">
          <el-icon><Connection /></el-icon>
          防火墙 {{ systemStatus.firewall ? '已启用' : '已关闭' }}
        </el-tag>
        <el-button type="danger" plain @click="handleEmergencyShutdown">
          <el-icon><SwitchButton /></el-icon>
          紧急熔断
        </el-button>
      </div>
    </div>

    <!-- 核心指标 -->
    <el-row :gutter="20" class="metric-row">
      <el-col :xs="24" :sm="8" :md="6" v-for="(metric, index) in metrics" :key="index">
        <div class="metric-card" :class="metric.status">
          <div class="metric-header">
            <el-icon :class="metric.status"><component :is="metric.icon" /></el-icon>
            <span class="metric-title">{{ metric.title }}</span>
          </div>
          <div class="metric-value">
            {{ metric.formattedValue }}{{ metric.unit }}
          </div>
          <div class="metric-footer">
            <span class="metric-label">{{ metric.label }}</span>
            <el-progress
              :percentage="metric.percentage"
              :color="metric.status === 'danger' ? '#ff4d4f' : '#13c2c2'"
              :stroke-width="8"
              :show-text="false"
            />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 可视化图表 -->
    <div class="chart-container">
      <div class="chart-wrapper">
        <h3 class="chart-title"><el-icon><DataAnalysis /></el-icon> 威胁攻击趋势</h3>
        <div ref="threatChartRef" class="chart"></div>
      </div>
      <div class="chart-wrapper">
        <h3 class="chart-title"><el-icon><PieChart /></el-icon> 访问来源分析</h3>
        <div ref="accessChartRef" class="chart"></div>
      </div>
    </div>

    <!-- 实时事件面板 -->
    <div class="event-panel">
      <div class="event-list">
        <h3><el-icon><Bell /></el-icon> 实时安全事件 <el-tag type="warning" size="small">最新{{ events.length }}条</el-tag></h3>
        <div class="event-scroll">
          <div
            v-for="(event, index) in events"
            :key="index"
            class="event-item"
            :class="event.type"
          >
            <el-icon class="event-icon"><component :is="eventIcons[event.type as keyof typeof eventIcons]" /></el-icon>
            <div class="event-content">
              <div class="event-header">
                <span class="event-time">{{ event.time }}</span>
                <el-tag
                  :type="event.type === 'attack' ? 'danger' : 'warning'"
                  size="small"
                  effect="plain"
                >
                  {{ eventTypes[event.type] }}
                </el-tag>
              </div>
              <div class="event-message">{{ event.message }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 控制面板 -->
      <div class="control-panel">
        <h3><el-icon><Operation /></el-icon> 安全控制</h3>
        <div class="control-buttons">
          <el-button
            type="danger"
            plain
            class="control-btn"
            @click="toggleFirewall"
          >
            <el-icon><Switch /></el-icon>
            {{ systemStatus.firewall ? '关闭' : '开启' }}防火墙
          </el-button>
          <el-button
            type="warning"
            plain
            class="control-btn"
            @click="refreshCertificates"
          >
            <el-icon><Refresh /></el-icon>
            刷新证书
          </el-button>
          <el-button
            type="info"
            plain
            class="control-btn"
            @click="showLogs"
          >
            <el-icon><Document /></el-icon>
            审计日志
          </el-button>
        </div>
        <div class="status-indicator">
          <el-icon :class="systemStatus.encryption ? 'safe' : 'danger'"><Lock /></el-icon>
          <span>数据传输加密：{{ systemStatus.encryption ? '已启用' : '未启用' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import {
  Monitor,
  Connection,
  SwitchButton,
  DataAnalysis,
  PieChart,
  Bell,
  Operation,
  Switch,
  Refresh,
  Document,
  Lock,
  Warning,
  CircleCloseFilled
} from '@element-plus/icons-vue'

// 系统状态
const systemStatus = reactive({
  firewall: true,
  encryption: true,
  lastBreach: '2023-09-15 14:30:00'
})

// 核心指标数据
const metrics = reactive([
  {
    title: '异常请求',
    icon: Warning,
    value: 42,
    formattedValue: computed((): number => metrics[0].value),
    unit: '次/小时',
    status: 'danger',
    percentage: 70,
    label: '较上小时 +12%'
  },
  {
    title: '数据加密率',
    icon: Lock,
    value: 98.345,
    formattedValue: computed((): string => metrics[1].value.toFixed(2)),
    unit: '%',
    status: 'safe',
    percentage: 98,
    label: '符合安全标准'
  },
  {
    title: '证书有效期',
    icon: CircleCloseFilled,
    value: 27,
    formattedValue: computed((): number => Math.floor(metrics[2].value)),
    unit: '天',
    status: 'warning',
    percentage: 90,
    label: '即将到期提醒'
  }
])

// 安全事件数据
const events = ref([
  {
    time: '14:25:36',
    type: 'attack',
    message: '检测到异常登录尝试（来源IP：192.168.1.45）'
  },
  {
    time: '14:22:15',
    type: 'warning',
    message: '/api/v1/data 接口请求频率超限'
  },
  {
    time: '14:20:09',
    type: 'attack',
    message: 'SQL注入攻击拦截（路径：/search）'
  }
])

const eventIcons = {
  attack: Warning,
  warning: Bell
}

const eventTypes: { [key: string]: string } = {
  attack: '攻击事件',
  warning: '安全警告'
}

// 图表实例
let threatChart: ECharts | null = null
let accessChart: ECharts | null = null
const threatChartRef = ref<HTMLElement | null>(null)
const accessChartRef = ref<HTMLElement | null>(null)

// 初始化图表
const initCharts = () => {
  // 威胁攻击趋势图
  if (threatChartRef.value) {
    threatChart = echarts.init(threatChartRef.value)
    const initialData = [12, 15, 8, 24, 32, 28, 19, 22, 35, 29, 36, 40]
    threatChart.setOption({
      tooltip: {
        trigger: 'axis',
        formatter: '{b0}<br/>攻击次数: {c0} 次'
      },
      grid: {
        top: '10%',
        right: '2%',
        bottom: '11%',
        left: '7%'
      },
      xAxis: {
        type: 'category',
        data: generateTimeSeries(12),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value',
        name: '攻击次数/小时'
      },
      series: [{
        name: '攻击次数',
        type: 'line',
        smooth: true,
        areaStyle: { color: 'rgba(255,77,79,0.2)' },
        lineStyle: { color: '#ff4d4f' },
        itemStyle: { color: '#ff4d4f' },
        data: initialData
      }]
    })
  }

  // 访问来源分析图
  if (accessChartRef.value) {
    accessChart = echarts.init(accessChartRef.value)
    accessChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 20
      },
      series: [{
        type: 'pie',
        radius: ['50%', '80%'],
        data: [
          { value: 335, name: '正常流量' },
          { value: 135, name: '可疑请求' },
          { value: 68, name: '攻击流量' }
        ],
        itemStyle: {
          color: ({ name }: { name: string }) => {
            switch(name) {
              case '正常流量': return '#ff7875'
              case '可疑请求': return '#a8071a'
              default: return '#5c0011'
            }
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    })
  }
}

// 生成时间序列数据
const generateTimeSeries = (count: number) => {
  const now = new Date()
  return Array.from({ length: count }, (_, i) => {
    const d = new Date(now.getTime() - (count - i - 1) * 3600000)
    return `${d.getHours().toString().padStart(2, '0')}:00`
  })
}

// 模拟实时数据更新
let dataTimer: number
const updateMetrics = () => {
  // 异常请求
  metrics[0].value = Math.min(99, metrics[0].value + Math.floor(Math.random() * 3))
  metrics[0].percentage = Math.min(100, metrics[0].percentage + 2)

  // 数据加密率（保留两位小数）
  metrics[1].value = parseFloat((97 + Math.random() * 3).toFixed(2))

  // 证书有效期（整数天数）
  metrics[2].value = Math.max(0, metrics[2].value - 0.1)
  metrics[2].formattedValue = Math.floor(metrics[2].value)

  // 更新攻击趋势图
  if (threatChart) {
    const option = threatChart.getOption() as { series: any[]; xAxis: any[] }
    const newData = [...option.series[0].data, Math.floor(Math.random() * 40) + 10]
    const newTime = new Date().toLocaleTimeString('en-US', { hour12: false })

    threatChart.setOption({
      xAxis: [{
        data: [...option.xAxis[0].data.slice(1), newTime]
      }],
      series: [{
        data: newData.slice(-24)
      }]
    })
  }

  // 添加事件
  if (Math.random() > 0.7) {
    events.value.unshift({
      time: new Date().toLocaleTimeString(),
      type: Math.random() > 0.8 ? 'attack' : 'warning',
      message: generateEventMessage()
    })
    if (events.value.length > 10) events.value.pop()
  }
}

// 生成随机事件消息
const generateEventMessage = () => {
  const events = [
    '检测到异常端口扫描活动',
    '来自异常地理位置的登录尝试',
    'API接口请求频率超限',
    '检测到XSS攻击尝试',
    '数据库连接数异常增加'
  ]
  const ips = ['192.168.1.', '10.0.0.', '172.16.0.'].map(p => p + Math.floor(Math.random() * 255))
  return `${events[Math.floor(Math.random() * events.length)]}（来源IP：${ips[Math.floor(Math.random() * ips.length)]}）`
}

// 安全控制方法
const toggleFirewall = () => {
  systemStatus.firewall = !systemStatus.firewall
  ElMessage.success(`防火墙已${systemStatus.firewall ? '启用' : '关闭'}`)
}

const refreshCertificates = () => {
  metrics[2].value = 30
  ElMessage.success('SSL证书已成功续期')
}

const handleEmergencyShutdown = () => {
  ElMessageBox.confirm('此操作将立即切断所有外部连接，是否继续？', '紧急熔断', {
    confirmButtonText: '确认熔断',
    cancelButtonText: '取消',
    type: 'error',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    systemStatus.firewall = true
    metrics[0].value = 0
    ElMessage({ type: 'success', message: '已执行网络熔断操作', duration: 3000 })
  })
}

const showLogs = () => {
  ElMessage.info('审计日志功能正在开发中，敬请期待')
}

// 生命周期
onMounted(() => {
  initCharts()
  dataTimer = window.setInterval(updateMetrics, 3000)
})

onBeforeUnmount(() => {
  clearInterval(dataTimer)
  threatChart?.dispose()
  accessChart?.dispose()
})
</script>

<style lang="scss" scoped>
.security-monitor {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 2px solid #ffccc7;

    .title-group {
      display: flex;
      align-items: center;
      gap: 12px;

      .main-icon {
        color: #ff4d4f;
        font-size: 36px;
      }

      h1 {
        margin: 0;
        color: #ff4d4f;
        font-size: 24px;
      }
    }

    .status-group {
      display: flex;
      gap: 16px;
      align-items: center;

      .status-tag {
        font-size: 14px;
        padding: 8px 12px;
      }
    }
  }

  .metric-row {
    margin-bottom: 24px;

    .metric-card {
      background: var(--detail-section-background);
      border-radius: 8px;
      padding: 16px;
      border-left: 4px solid;
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-2px);
      }

      &.danger { border-color: #ff4d4f; }
      &.safe { border-color: #52c41a; }
      &.warning { border-color: #faad14; }

      .metric-header {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .el-icon {
          font-size: 28px;
          margin-right: 8px;
          padding: 5px;
          border-radius: 6px;

          &.danger { color: #ff4d4f; background: #ff4d4f20; }
          &.safe { color: #52c41a; background: #52c41a20; }
          &.warning { color: #faad14; background: #faad1420; }
        }

        .metric-title {
          font-weight: 500;
        }
      }

      .metric-value {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 8px;

        &.danger { color: #ff4d4f; }
        &.safe { color: #52c41a; }
        &.warning { color: #faad14; }
      }

      .metric-footer {
        .metric-label {
          display: block;
          font-size: 12px;
          margin-bottom: 4px;
        }

        .el-progress {
          :deep(.el-progress-bar) {
            padding-right: 0;
          }
        }
      }
    }
  }

  .chart-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 24px;
    margin-bottom: 24px;

    .chart-wrapper {
      background: var(--detail-section-background);
      border-radius: 8px;
      padding: 16px;

      .chart-title {
        margin: 0 0 16px;
        color: #ff4d4f;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .chart {
        height: 300px;
        min-width: 300px; /* 添加最小宽度 */
      }
    }
  }

  .event-panel {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;

    @media (max-width: 992px) {
      grid-template-columns: 1fr;
    }

    .event-list {
      background: var(--detail-section-background);
      border-radius: 8px;
      padding: 16px;

      h3 {
        margin: 0 0 12px;
        color: #ff4d4f;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .event-scroll {
        height: 300px;
        overflow-y: auto;

        .event-item {
          background: var(--background-color);
          border-radius: 6px;
          padding: 12px;
          margin-bottom: 8px;
          transition: all 0.3s;

          &:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          }

          &.attack { border-left: 3px solid #ff4d4f; }
          &.warning { border-left: 3px solid #faad14; }

          .event-icon {
            font-size: 18px;
            margin-right: 12px;

            &.attack { color: #ff4d4f; }
            &.warning { color: #faad14; }
          }

          .event-content {
            flex: 1;

            .event-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 4px;

              .event-time {
                font-size: 12px;
              }
            }

            .event-message {
              font-size: 13px;
              line-height: 1.4;
            }
          }
        }
      }
    }

    .control-panel {
      background: var(--detail-section-background);
      border-radius: 8px;
      padding: 16px;

      h3 {
        margin: 0 0 16px;
        color: #ff4d4f;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .control-buttons {
        display: grid;
        gap: 12px;
        margin-bottom: 20px;

        .control-btn {
          width: 100%;
          justify-content: flex-start;
          padding: 12px 16px;
        }
      }

      .status-indicator {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 12px;
        background: var(--border-color);
        border-radius: 6px;

        .el-icon {
          font-size: 20px;

          &.safe { color: #52c41a; }
          &.danger { color: #ff4d4f; }
        }

        span {
          font-size: 13px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .security-monitor {
    padding: 16px;

    .header {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;

      .title-group h1 {
        font-size: 20px;
      }
    }

    .metric-row .el-col {
      margin-bottom: 16px;
    }
  }
}
</style>
